<?php

namespace app\logic\checkin;

use app\admin\model\checkin\Record as CheckinRecord;
use app\admin\model\checkin\Config as CheckinConfig;
use app\logic\BaseLogic;

class CheckinLogic extends BaseLogic
{
    /**
     * 用户签到逻辑
     *
     * @param int $user_id 用户ID
     * @return array 签到结果
     */
    public function checkin(int $user_id): array
    {
        $output = [
            'status' => false,
            'message' => '',
            'data' => []
        ];

        // 获取当前时间（精确到天）
        $currentDate = strtotime(date('Y-m-d'));

        // 检查用户最后一次签到记录
        $lastCheckin = CheckinRecord::where('user_id', $user_id)
            ->order('checkin_time', 'desc')
            ->find();

        if ($lastCheckin) {
            // 检查是否已经签到
            $lastCheckinDate = strtotime(date('Y-m-d', strtotime($lastCheckin->checkin_time)));
            if ($lastCheckinDate === $currentDate) {
                $output['message'] = __('You have already checked in today');
                return $output;
            }

            // 判断是否为连续签到
            $isConsecutive = ($lastCheckinDate === $currentDate - 86400);
            $consecutiveDays = $isConsecutive ? $lastCheckin->consecutive_days + 1 : 1;
        } else {
            // 第一次签到
            $consecutiveDays = 1;
        }

        // 从配置表中获取奖励信息
        $rewardConfig = CheckinConfig::where('days', '<=', $consecutiveDays)
            ->where('status', 1)
            ->order('days', 'desc') // 优先选择匹配的最大天数
            ->find();

        if (!$rewardConfig) {
            $output['message'] = __('No check-in rewards configured');
            return $output;
        }

        // 计算奖励
        $rewardType = $rewardConfig->reward_type;

        // 处理 reward_num，当 reward_type=3 时随机选择
        if ($rewardType == 3) {
            $rewardOptions = explode('|', $rewardConfig->reward_num); // 分割 reward_num
            $rewardNum = (int)$rewardOptions[array_rand($rewardOptions)]; // 随机选择一个值
        } else {
            $rewardNum = (int)$rewardConfig->reward_num * $rewardConfig->reward_multiple;
        }

        // 插入签到记录
        $record = new CheckinRecord();
        $record->user_id = $user_id;
        $record->checkin_time = time();
        $record->consecutive_days = $consecutiveDays;
        $record->reward_type = $rewardType;
        $record->reward = $rewardNum;

        if ($record->save()) {
            $output['status'] = true;
            $output['message'] = __('Check-in successful');
            $output['data'] = [
                'consecutive_days' => $consecutiveDays,
                'reward_type' => $rewardType,
                'reward' => $record->reward
            ];
        } else {
            $output['message'] = __('Check-in failed. Please try again later');
        }

        return $output;
    }
}
